<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { loginByQQ, sendMobileCode, bindMobile } from '@/services/user'
import { useRouter } from 'vue-router'
import { mobileRules, codeRules } from '@/utils/rules'
import { showFailToast, showToast, showSuccessToast, type FormInstance } from 'vant'
import 'vant/es/toast/style';
const router = useRouter()
// 是否需要进行手机号码绑定，默认不需要
const isBind = ref(false)
const openId = ref('')
onMounted(() => {
  // 检测QQ是否登录成功
  if (window.QC.Login.check()) {
    // 获取openId
    window.QC.Login.getMe(async (id) => {
      openId.value = id
      try {
        // 调qq登录接口
        const { data } = await loginByQQ(id)
        loginSuccess(data)
      } catch (err) {
        // 说明未和手机号码进行绑定
        // 需要进行绑定
        isBind.value = true
      }
    })
  }
})

// 表单相关操作
const mobile = ref('')
const code = ref('')
const bind = async () => {
  const { data } = await bindMobile(
    {
      mobile: mobile.value,
      code: code.value,
      openId: openId.value
    }
  )
  loginSuccess(data)
}

// 处理登录成功后的操作
const store = useUserStore()
const loginSuccess = (u: User) => {
  // 存用户信息到pinia中
  store.setUser(u)
  // 提示
  showSuccessToast('登录成功')
  // push() 跳转到某个路由，可以通过返回键重新回来，也就是说浏览器会保留历史访问记录方便回退
  // router.push('')
  // replace() 跳转到某个路由，不能通过返回键重新回来，也就是说浏览器不会保留历史访问记录
  // 回调到个人中心或者上次登录时的地址
  router.replace(store.returnUrl || '/user')
}

// 发送短信验证码
import { useInterVal } from '@/hooks/index'
import type { User } from '@/types/user'
import { useUserStore } from '@/stores'
const loginFormRef = ref<null | FormInstance>(null)
const { time, start } = useInterVal()
const send = async () => {
  // 1.如果短信倒计时正在进行中，不应该再次发送短信验证码
  if (time.value > 0) return
  // 2.输入的手机号码必须是正确的格式
  await loginFormRef.value!.validate('mobile')
  // 3.发送《绑定》短信
  sendMobileCode(mobile.value, 'bindMobile').then(() => {
    showSuccessToast('发送短信成功')
    // 4.开启短信倒计时
    start()
  })
}

</script>

<template>
  <div class="login-page" v-if="isBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="loginFormRef" @submit="bind">
      <van-field v-model="mobile" name="mobile" :rules="mobileRules" placeholder="请输入手机号"></van-field>
      <van-field v-model="code" name="code" :rules="codeRules" placeholder="请输入验证码">
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}
          </span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit"> 立即绑定 </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import url('./index.scss');
</style>
